package transforms;
import java.util.Iterator;

import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodNode;

import com.rshacking.rhf.files.ClassContainer;
import com.rshacking.rhf.unification.InstructionItem;
import com.rshacking.rhf.updater.Transform;
import com.rshacking.rhf.updater.hooks.ClassHook;
import com.rshacking.rhf.updater.hooks.HooksList;
import com.rshacking.rhf.updater.instructions.InsnCondition;
import com.rshacking.rhf.updater.instructions.InstructionFinder;
import com.rshacking.rhf.updater.instructions.RegexInsnFinder;

public class AnimableTransforms extends Transform {

	@Override
	public boolean canActivate(HooksList hooks, ClassContainer cc) {
		ClassHook an = hooks.get("AnimableNode");
		if (an == null)
			return false;
		String checkk = "L" + an.getOrigName() + ";";
		String check2 = "(IL";
		for (MethodNode mn : cc.getASM().methods) {
			if (mn.getMethodDesc().contains(checkk) && mn.getMethodDesc().contains(check2))
				return true;
		}
		return false;
	}

	@Override
	public boolean execute(HooksList hooks, ClassContainer cc) {
		ClassHook c = hooks.get("AnimableNode");
		
		String checkk = "L" + c.getOrigName() + ";";
		String check2 = "(IL";

		Iterator<MethodNode> methods = cc.getASM().methods.iterator();
		while (methods.hasNext()) {
			MethodNode method = methods.next();

			if (method.getMethodDesc().contains(checkk) && method.getMethodDesc().contains(check2)) {
				InstructionFinder<AbstractInsnNode> finder = new InstructionFinder<AbstractInsnNode>(
						method, true);
				FieldInsnNode fin = null;

				fin = (FieldInsnNode) finder
						.getNext(InsnCondition.ASM.PUTFIELD_L);

				if (fin != null) {
					c.add("nextNode", fin);
				}

				fin = (FieldInsnNode) finder
						.getNext(InsnCondition.ASM.PUTFIELD_L);
				if (fin != null) {
					if (!hooks.contains("Animable"))
						hooks.add("Animable", fin.desc);
					c.add("currentAnimable", fin);
				}

				return true;
			}
		}
		return false;
	}
}